package raft.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import raft.entity.LogEntry;
import raft.service.StateMachine;

public class StateMachineImpl implements StateMachine {

    private RocksDB rocksDB;





    public static StateMachineImpl getInstance(){
        return DefaultStateMachine.INSTANCE;
    }

    private static class DefaultStateMachine{
        private static final StateMachineImpl INSTANCE = new StateMachineImpl();
    }

    @Override
    public synchronized void apply(LogEntry logEntry) {

        try {
            if(logEntry.getCommand() == null){
                return;
            }

            rocksDB.put(logEntry.getCommand().getKey().getBytes(), JSON.toJSONBytes(logEntry));

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public LogEntry get(String key) {

        try {

            byte[] log = rocksDB.get(key.toString().getBytes());
            if(log == null){
                return null;
            }
            return JSONObject.parseObject(log,LogEntry.class);
        }catch (RocksDBException e){
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public String getString(String key) {
        return null;
    }

    @Override
    public void setString(String key, String value) {

    }

    @Override
    public void delString(String... key) {

    }
}
